<template>
    <view style="display: flex;">
        <view class="footer">
            <u-button @click="clear" style="flex: 0 0 20%; display: flex; flex-direction: column;">
                <text style="transform: rotate(90deg);">重</text>
                <text style="transform: rotate(90deg);">置</text>
            </u-button>
            <u-button type="primary" @click="finish" style="flex: 0 0 20%; display: flex; flex-direction: column;">
                <text style="transform: rotate(90deg);">保</text>
                <text style="transform: rotate(90deg);">存</text>
            </u-button>
        </view>
        <canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
            @touchend="touchend"></canvas>
    </view>
</template>

<script>
var x = 20;
var y = 20;
import {apiConfig} from '@/utils/apiConfig'
import { getAccessToken } from '@/utils/auth'
import { signatureSign, socialAuthRedirect } from '@/api/user'
export default {
    data() {
        return {
            ctx: '',
            points: [],
            uploading: false,
            contractId: '',
            signatureType: '',
            hasSignature: false
        }
    },
    mounted() {
        this.ctx = uni.createCanvasContext("mycanvas", this);   //创建绘图对象

        //设置画笔样式
        this.ctx.lineWidth = 4;
        this.ctx.lineCap = "round"
        this.ctx.lineJoin = "round"
    },
    onLoad(options) {
        this.contractId = options.contractId
        this.signatureType = options.signatureType
    },
    methods: {
        socialAuthRedirect() {
            socialAuthRedirect({
                type: '31',
                redirectUri: `${window.location.origin}/pages/pay/index`
            }).then(res => {
                window.location = res.data.data
            })
        },
        //触摸开始，获取到起点
        touchstart: function (e) {
            e.preventDefault()
            let startX = e.changedTouches[0].x;
            let startY = e.changedTouches[0].y;
            let startPoint = { X: startX, Y: startY };
            this.points.push(startPoint);
            //每次触摸开始，开启新的路径
            this.ctx.beginPath();
        },

        //触摸移动，获取到路径点
        touchmove: function (e) {
            e.preventDefault()
            let moveX = e.changedTouches[0].x;
            let moveY = e.changedTouches[0].y;
            let movePoint = { X: moveX, Y: moveY };
            this.points.push(movePoint);       //存点
            let len = this.points.length;
            if (len >= 2) {
                this.draw();                   //绘制路径
            }

        },
        touchend: function () {
            this.points = [];
            this.hasSignature = true
        },

        draw: function () {
            let point1 = this.points[0]
            let point2 = this.points[1]
            this.points.shift()
            this.ctx.moveTo(point1.X, point1.Y)
            this.ctx.lineTo(point2.X, point2.Y)
            this.ctx.stroke()
            this.ctx.draw(true)
        },

        //清空画布
        clear: function () {
            let that = this;
            uni.getSystemInfo({
                success: function (res) {
                    let canvasw = res.windowWidth;
                    let canvash = res.windowHeight;
                    that.ctx.clearRect(0, 0, canvasw, canvash);
                    that.ctx.draw(true);
                },
            })
        },

        //完成绘画并上传图片
        finish: function () {
            if (!this.hasSignature) {
                uni.showToast({
                    title: '请先进行签名',
                    icon: 'none'
                });
                return;
            }
            uni.canvasToTempFilePath({
                canvasId: 'mycanvas',
                success: (res) => {
                    console.log(res)
                    let path = res.tempFilePath;
                    console.log(path)
                    this.uploadImage(path)
                }
            })
        },
        onSignatureSaved(signatureImage) {
            console.log('获取到签名图片:', signatureImage)
            signatureSign({
                "contractId": this.contractId,
                "signatureImage": signatureImage,
                "signatureType": this.signatureType
            }).then(res => {
                console.log(res.data.data.orderId)
                uni.setStorageSync('orderId', res.data.data.orderId)
                uni.setStorageSync('contractId', this.contractId)
                if (this.signatureType == 'borrower') {
                    this.socialAuthRedirect()
                } else {
                    uni.navigateTo({
                        url: '/pages/contract/detail?id=' + this.contractId
                    })
                }
            })
        },
        uploadImage(filePath) {
            this.uploading = true;
            uni.showLoading({
                title: '上传中...'
            });

            uni.uploadFile({
                timeout: 10000,
                url: apiConfig.baseUrl + '/app-api/infra/file/upload',
                filePath: filePath,
                name: 'file',
                header: {
                    'Authorization': 'Bearer ' + getAccessToken(),
                    'tenant-id': apiConfig.tenantId
                },
                method: 'post',
                success: (res) => {
                    console.log(res.data.data)
                    const data = JSON.parse(res.data)
                    this.onSignatureSaved(data.data)
                },
                fail: () => {
                    uni.showToast({
                        title: '上传失败',
                        icon: 'none'
                    });
                },
                complete: () => {
                    this.uploading = false;
                    uni.hideLoading();
                }
            })
        },
    },
}
</script>

<style>
.title {
    height: 50upx;
    line-height: 50upx;
    font-size: 16px;
}

.mycanvas {
    flex: 0 0 90vw;
    height: 100vh;
    touch-action: none;
    background: #d3d3d3;
}

.footer {
    display: flex;
    padding: 10px;
    align-items: center;
    justify-content: space-around;
    flex-direction: column;
}

.left,
.right {
    line-height: 100upx;
    height: 100upx;
    width: 250upx;
    text-align: center;
    font-weight: bold;
    color: white;
    border-radius: 5upx;
}

.left {
    background: #007AFF;
}

.right {
    background: orange;
}
</style>
